﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace NZBMatrixAdvancedFeedReader.Classes
{
    internal class SystemSettings
    {
        
        #region Constructor

        static SystemSettings()
        {
            //  Setup default value for default search template.
            RefreshPeriod = 20;
            MaxPostAge = 1700;

            NZBMatrix.UserName = "unknown";
            NZBMatrix.APIKey = "unknown";

            SearchTemplateList = new List<SearchTemplate>();

        }

        #endregion

        #region Properties

        /// <summary>
        /// The period it takes to run the search query again in seconds.
        /// </summary>
        public static int RefreshPeriod { get; set; }

        /// <summary>
        /// Max Post age from NZBMatrix. It depends on your configurations in your usenet account.
        /// </summary>
        public static int MaxPostAge { get; set; }

        public static Classes.SearchTemplate SelectedTemplate { get; set; }

        public static List<Classes.SearchTemplate> SearchTemplateList { get; set; }

        public class NZBMatrix
        {
            public static string UserName { get; set; }
            public static string APIKey { get; set; }
        }

        #endregion

        #region Public Methods
        /// <summary>
        /// Loads the settings from the config file.
        /// </summary>
        public static void LoadSettings()
        {

            string fileName;
            XDocument xd;
            XElement xnApplication;

            fileName = Path.Combine(Directory.GetCurrentDirectory(), "SystemSettings.xml");

            if (File.Exists(fileName))
            {

                try
                {

                    xd = XDocument.Load(fileName);



                    xnApplication = xd.Element("Application");
                    SystemSettings.RefreshPeriod = int.Parse(xnApplication.Element("RefreshPeriod").Value);
                    SystemSettings.MaxPostAge = int.Parse(xnApplication.Element("MaxPostAge").Value);

                    SystemSettings.NZBMatrix.UserName = xnApplication.Element("NZBMatrix").Attribute("UserName").Value;
                    SystemSettings.NZBMatrix.APIKey = xnApplication.Element("NZBMatrix").Attribute("APIKey").Value;

                    SearchTemplateList.Clear();

                    //  Load All Templates;
                    foreach (XElement xn in xnApplication.Element("SearchTemplates").Elements())
                    {
                        SearchTemplate st = new SearchTemplate();
                        st.Name = xn.Attribute("Name").Value;
                        st.LinkType = (SearchTemplate.LinkTypes)System.Enum.Parse(typeof(SearchTemplate.LinkTypes), xn.Attribute("LinkType").Value);
                        st.EnglishOnly = bool.Parse(xn.Attribute("EnglishOnly").Value);
                        st.UseSSL = bool.Parse(xn.Attribute("UseSSL").Value);
                        st.PreserveFileName = bool.Parse(xn.Attribute("PreserveFileName").Value);
                        st.SearchMethod = (SearchTemplate.SearchMethods)System.Enum.Parse(typeof(SearchTemplate.SearchMethods), xn.Attribute("SearchMethod").Value);
                        st.SearchTerm =  xn.Attribute("SearchTerm").Value ;
                        st.MaxPostAge = SystemSettings.MaxPostAge;
                        st.Categories = xn.Attribute("Categories").Value;
                        st.HasMovieYearLimit = bool.Parse(xn.Attribute("MovieYear").Value);
                        if (st.HasMovieYearLimit)
                        {
                            st.MovieYearFrom = xn.Attribute("MovieYearFrom").Value;
                            st.MovieYearTo = xn.Attribute("MovieYearTo").Value;
                        }
                        st.HasMovieRateLimit = bool.Parse(xn.Attribute("MovieRate").Value);
                        if (st.HasMovieRateLimit)
                        {
                            st.MovieRateFrom = xn.Attribute("MovieRateFrom").Value;
                            st.MovieRateTo = xn.Attribute("MovieRateTo").Value;
                        }
                        SearchTemplateList.Add(st);
                    }

                    string selectedTemplate = xnApplication.Element("SelectedTempate").Value;
                    SelectedTemplate = SearchTemplateList.FirstOrDefault(x => x.Name == selectedTemplate);


                }
                catch (Exception)
                {

                    if (MessageBox.Show("There is a problem with your config file. Please confirm to reset the file to the default state.", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                    {
                        SaveSettings();
                        LoadSettings();
                    }
                }

            }
        }

        /// <summary>
        /// Saves the settings into the config file.
        /// </summary>
        public static void SaveSettings()
        {

            string fileName;
            fileName = Path.Combine(Directory.GetCurrentDirectory(), "SystemSettings.xml");

            XDocument xd =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement("Application",
                        new XElement("RefreshPeriod", RefreshPeriod),
                        new XElement("MaxPostAge", MaxPostAge),
                        new XElement("NZBMatrix",
                                new XAttribute("UserName", NZBMatrix.UserName),
                                new XAttribute("APIKey", NZBMatrix.APIKey)
                                ),
                        new XElement("SelectedTempate", (SelectedTemplate == null ? "Default" : SelectedTemplate.Name)),
                        new XElement("SearchTemplates")
                        )
                    );

            //  Create default template if config file is damaged.
            if (SystemSettings.SearchTemplateList == null || SystemSettings.SearchTemplateList.Count == 0)
            {
                SystemSettings.SearchTemplateList = new List<SearchTemplate>();
                SystemSettings.SearchTemplateList.Add(new SearchTemplate()
                {
                    Name = "Default",
                    Categories = "1",
                    HasMovieYearLimit = false,
                    MovieYearFrom = "",
                    MovieYearTo = "",
                    HasMovieRateLimit = false,
                    MovieRateFrom = "",
                    MovieRateTo = "",
                    EnglishOnly = true,
                    LinkType = SearchTemplate.LinkTypes.NZBDownloadLink,
                    MaxPostAge = 1700,
                    PreserveFileName = false,
                    SearchMethod = SearchTemplate.SearchMethods.NZBName,
                    SearchTerm = "",
                    UseSSL = false
                });
            }

            foreach (SearchTemplate searchTemplate in SystemSettings.SearchTemplateList)
            {
                xd.Element("Application").Element("SearchTemplates").Add(
                    new XElement("SearchTemplate", searchTemplate.SearchTerm,
                                        new XAttribute("Name", searchTemplate.Name),
                                        new XAttribute("Categories", searchTemplate.Categories),
                                        new XAttribute("LinkType", searchTemplate.LinkType),
                                        new XAttribute("EnglishOnly", searchTemplate.EnglishOnly),
                                        new XAttribute("UseSSL", searchTemplate.UseSSL),
                                        new XAttribute("PreserveFileName", searchTemplate.PreserveFileName),
                                        new XAttribute("SearchMethod", searchTemplate.SearchMethod),
                                        new XAttribute("SearchTerm", searchTemplate.SearchTerm),
                                        new XAttribute("MovieYear", searchTemplate.HasMovieYearLimit),
                                        new XAttribute("MovieYearFrom", searchTemplate.MovieYearFrom),
                                        new XAttribute("MovieYearTo", searchTemplate.MovieYearTo),
                                        new XAttribute("MovieRate", searchTemplate.HasMovieRateLimit),
                                        new XAttribute("MovieRateFrom", searchTemplate.MovieRateFrom),
                                        new XAttribute("MovieRateTo", searchTemplate.MovieRateTo)
                                        )
                        );
            }


            xd.Save(fileName);

        }

        #endregion

    }
}

